package com.ruoci.redis.bloomfilter;

import com.ruoci.redis.response.BasicResponse;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author yang
 * redisson 实现布隆过滤器(缓存穿透-访问缓存和数据库都不存在的数据)
 **/
@Slf4j
@RestController
@RequestMapping("/redisson")
public class RedisController {

    @Resource
    private RedissonClient redisson;

    /**
     * 实现布隆过滤器
     * @return
     */
    @GetMapping("/filter")
    public BasicResponse redisson(){

        // 获取布隆过滤器
        RBloomFilter<String> bloomFilter = redisson.getBloomFilter("userList");
        //初始化布隆过滤器：预计元素为100L,误差率为3%
        long total = 100L;
        bloomFilter.tryInit(total,0.03);
        // 初始化数据到过滤器中
        for (int i = 0; i < total; i++) {
            bloomFilter.add("natalia" + i);
        }
        int count = 0;
        // 200 条数据进行去重校验
        long addCount = 2*total;
        for (int i = 0; i < addCount; i++) {
            if (bloomFilter.contains("natalia" + i)) {
                count++;
            }
        }
        // 匹配数量
        return BasicResponse.success("匹配数量 ".concat(String.valueOf(count)));
    }
}
